<template>
  <div>
    <div class="query">
      <el-input
        placeholder="请输入用户名称"
        style="width: 200px; margin-right: 13px"
        v-model="userQuery.username"
        clearable
      />
      <el-button @click="handleQuery">查询</el-button>
      <el-button type="primary" @click="handleAddRole" v-has="'sys-user-add'">新增</el-button>
    </div>

    <div class="table">
      <el-table
        :data="UserList"
        border
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="username" label="用户名称" align="center" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag class="ml-2" :type="`${scope.row.state ? '' : 'danger'}`">{{
              scope.row.state ? "启用" : "禁用"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_time" label="创建时间" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click.prevent="handleEditor(scope.row)"
              v-has="'sys-user-edit'"
            >
              编辑
            </el-button>

            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="red"
              :title="`确定重置密码?`"
              @confirm="handleResetPwd(scope.row)"
            >
              <template #reference>
                <el-button type="text" size="small" v-has="'sys-user-edit'">重置密码</el-button>
              </template>
            </el-popconfirm>

            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="red"
              :title="`确定${scope.row.state === 1 ? '禁用' : '启用'}此用户?`"
              @confirm="handledeleteRow(scope.row)"
            >
              <template #reference>
                <el-button type="text" size="small" v-has="'sys-user-del'">{{
                  scope.row.state === 1 ? "禁用" : "启用"
                }}</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <el-pagination
          background
          layout="prev, pager, next, jumper,total"
          :total="total"
          @current-change="handleCurrentChange"
          hide-on-single-page
        ></el-pagination>
      </div>
    </div>

    <el-dialog
      v-model="userState.dialogVisible"
      :title="userState.isAdd ? '新增' : '编辑'"
      width="40%"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        :rules="userState.rules"
        :model="userState.ruleForm"
        label-width="80px"
      >
        <div class="login-input">
          <el-form-item prop="username" label="昵称">
            <el-input
              placeholder="请输入昵称"
              v-model="userState.ruleForm.username"
              clearable
            />
          </el-form-item>

          <!-- <el-form-item prop="password" label="密码">
            <el-input
              placeholder="请输入密码"
              type="password"
              show-password
              :disabled="!userState.isAdd"
              v-model="userState.ruleForm.password"
              clearable
            />
          </el-form-item> -->

          <el-form-item prop="mobile" label="手机号">
            <el-input
              placeholder="请输入手机号"
              v-model="userState.ruleForm.mobile"
              clearable
            />
          </el-form-item>

          <el-form-item prop="role_id" label="角色">
            <el-radio-group v-model="userState.ruleForm.role_id">
              <el-radio
                v-for="item in roleList"
                :key="item.id"
                :label="item.id"
                >{{ item.role_name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleDetermine(ruleFormRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref, unref } from "vue";
import { InfoFilled } from "@element-plus/icons-vue";
import {
  queryUserByPage,
  userEdit,
  userAdd,
  roleQueryRoleByPage,
} from "../../api/user";
import type { ElForm } from "element-plus";

type FormInstance = InstanceType<typeof ElForm>;
const ruleFormRef = ref<FormInstance | any>();

onMounted(() => {
  handleGetUserList(); // 表格列表
  handleGetRole(); // 获取所有角色列表
});

const roleList = ref<any>([]);
// 获取所有角色
const handleGetRole = () => {
  roleQueryRoleByPage({ page: 1, limit: 1000 }).then(({ code, data }: any) => {
    if (code === 200) {
      roleList.value = data.rows;
    }
  });
};

const handleDetermine = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      const { username, password, mobile, role_id, editId } =
        userState.ruleForm;
      interface Params {
        username: string;
        password: string | number;
        mobile: number | string;
        role_id: string | number;
        state: number;
        id?: string;
      }
      const params: Params = {
        username,
        password,
        mobile,
        role_id,
        state: 1,
      };
      if (!userState.isAdd) params.id = editId;
      const { code }: any = userState.isAdd
        ? await userAdd(params)
        : await userEdit(params);
      if (code === 200) {
        ElMessage({
          message: `${userState.isAdd ? "创建" : "编辑"}用户成功`,
          type: "success",
        });
        userState.dialogVisible = false;
        userQuery.page = 1;
        total.value = 0;
        ruleFormRef.value.resetFields();
        handleGetUserList();
      }
    }
  });
};

// 新增 or 编辑用户窗口state
const userState = reactive({
  dialogVisible: <boolean>false,
  isAdd: true,
  ruleForm: {
    username: "",
    password: "",
    mobile: "",
    role_id: "",
    editId: "",
  },
  // 表单校验
  rules: {
    username: [
      {
        required: true,
        message: "请输入角色名称",
        trigger: "blur",
      },
    ],
    password: [],
    mobile: [
      {
        required: true,
        message: "请输入手机号",
        trigger: "blur",
      },
    ],
    role_id: [
      // {
      //   required: true,
      //   message: "请选择角色",
      //   trigger: "change",
      // },
    ],
  },
});

const handleClose = () => {
  const form = unref(ruleFormRef);
  form.resetFields();
  userState.dialogVisible = false;
  // ruleFormRef.value.resetFields();
};
// 用户列表数据
const UserList = ref([]);

// 表格tableLoading
const tableLoading = ref(false);

// 表格编辑
const handleEditor = (row: any) => {
  userState.dialogVisible = true;
  userState.isAdd = false;
  const { username, mobile, role_id, id } = row;
  userState.ruleForm.username = username;
  userState.ruleForm.mobile = mobile;
  userState.ruleForm.role_id = role_id;
  userState.ruleForm.editId = id;
};

// 表格禁用 or 启用按钮
const handledeleteRow = (row: any) => {
  const status = row.state;
  userEdit({ id: row.id, state: status === 1 ? 0 : 1 }).then(
    ({ code }: any) => {
      if (code == 200) {
        handleGetUserList();
      }
    }
  );
};

// 重置密码
const handleResetPwd = (row: any) => {
  userEdit({ id: row.id, password: "123456" }).then(({ code }: any) => {
    if (code == 200) {
      ElMessage({
        message: "重置密码成功",
        type: "success",
      });
      handleGetUserList();
    }
  });
};

// 表格分页
const handleCurrentChange = (currentPageNum: number) => {
  userQuery.page = currentPageNum;
  handleGetUserList();
};

// 新增用户
const handleAddRole = () => {
  userState.dialogVisible = true;
  console.log("handleAddRole");
};

// 查询按钮
const handleQuery = () => {
  userQuery.page = 1;
  handleGetUserList();
  console.log("handleQuery");
};

interface UserTy {
  page: number;
  limit: number;
  username: string;
}

const userQuery: UserTy = reactive({
  page: 1,
  limit: 10,
  username: "",
});
const total = ref(0);
// 获取用户list
const handleGetUserList = () => {
  tableLoading.value = true;
  queryUserByPage(userQuery).then((res: any) => {
    if (res.code === 200) {
      total.value = res.data.count;
      tableLoading.value = false;
      UserList.value = res.data.rows;
    }
  });
};
</script>

<style lang="scss" scoped></style>
